package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.ApplicationForm;
import com.letv.whatslive.model.convert.ApplicationFormConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by liyulin on 2016/5/16.
 */
@Repository
public class ApplicationFormDAO extends BaseDAO {
    protected String collectionName = "applicationForm";

    private static final Logger logger = LoggerFactory.getLogger(ApplicationFormDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public long insertApplicationForm(ApplicationForm applicationForm) {
        applicationForm.setCreateTime(System.currentTimeMillis());
        DBObject obj = ApplicationFormConvert.castApplicationFormToDBOjbect(applicationForm);
        return this.insert(obj);
    }

    /**
     * 根据活动Id和用户Id查询报名信息
     *
     * @param activityId
     * @param userId
     * @return
     */
    public DBObject getApplicationFromByActivityIdAndUserId(Long activityId, Long userId) {
        DBObject query = new BasicDBObject();
        query.put("activityId", activityId);
        query.put("userId", userId);
        DBObject result = dbCollection.findOne(query);
        return result;
    }

    /**
     * 查询报名表列表
     * @param orders
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<ApplicationForm> getApplicationFormListByParams(Map<String, Object> orders, Map<String, Object> params, Integer start, Integer limit) {

        List<ApplicationForm> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                ApplicationForm applicationForm = ApplicationFormConvert.castDBObjectToApplicationForm(dbObject);
                setValueToApplicationForm(applicationForm);
                result.add(applicationForm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 查询活动报名表的记录数
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countApplicationFormByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("name") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("name") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("name", pattern);
            }
            if (params.get("activityId") != null) {
                query.put("activityId", ObjectUtils.toLong(params.get("activityId")));
            }
            if (params.get("userId") != null) {
                query.put("userId", ObjectUtils.toLong(params.get("userId")));
            }
        }
        return query;
    }
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }
    /**
     * 设置活动报名表信息中的特殊值
     * @param applicationForm
     */
    private void setValueToApplicationForm(ApplicationForm applicationForm) {
        applicationForm.setCreateTimeStr(applicationForm.getCreateTime() != null ?
                DateUtils.long2YMDHMS(applicationForm.getCreateTime()) : "");
    }

    public List<ApplicationForm> getAllApplicationForms(Map<String, Object> params) {
        List<ApplicationForm> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                ApplicationForm applicationForm = ApplicationFormConvert.castDBObjectToApplicationForm(dbObject);
                result.add(applicationForm);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }
}
